package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> findAll() {
        List<User> list = new ArrayList<>();
        String url = "jdbc:mysql://localhost:3306/jdbc";
        String user = "root";
        String password = "lihao040325";
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = java.sql.DriverManager.getConnection(url, user, password);
            String sql = "select * from user";
            ps = con.prepareStatement(sql);
            rs = ps.executeQuery();

            while (rs.next()) {
                User user1 = new User();
                user1.setId(rs.getInt("id"));
                user1.setName(rs.getString("name"));
                user1.setPassword(rs.getString("password"));
                list.add(user1);
            }
            return list;  // 正常执行时返回list
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();  // 异常时返回空列表
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            return new ArrayList<>();  // 异常时返回空列表
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (ps != null) {
                    ps.close();
                }
                if (con != null) {
                    con.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
